package com.itttq.tools.mybatis.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.itttq.tools.mybatis.to.FieldTo;
import com.itttq.tools.mybatis.to.GeneratorTo;
import com.itttq.tools.mybatis.to.ProjectTo;
import com.itttq.tools.mybatis.util.DataSourceTo;
import com.itttq.tools.mybatis.util.DbConstant;
import com.itttq.tools.mybatis.util.DbUtil;
import com.itttq.tools.mybatis.util.StringUtil;

public class TableInfo {
    private static final String importDate = "java.util.Date";
    private static final String importBigDecimal = "java.math.BigDecimal";
    private static final String dbUrl = "jdbc:mysql://%s:%s/%s?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&autoReconnectForPools=true";
    public static final String DOT = ".";
    public static final String SLASH = "/";
    
    public static DbUtil getDbUtil(ProjectTo project) {
        DataSourceTo ds = new DataSourceTo();
        ds.setDriver("com.mysql.jdbc.Driver");
        ds.setUrl(String.format(dbUrl, project.getDbHost(), project.getDbPort(), project.getDbName()));
        ds.setUsername(project.getDbUserName());
        ds.setPassword(project.getDbPassword());
        return new DbUtil(ds);
    }

    /**
     * 生成java文件
     *
     * @auther <a href="mailto:g2room@163.com">天涯</a>
     * Jan 9, 2014 5:08:05 PM
     */
    public static List<GeneratorTo> getTableInfo(ProjectTo project) {
        DbUtil dbUtil = getDbUtil(project);
        Map<String, String> tables = dbUtil.getTablesByStatus();

        boolean isComment = true;
        List<GeneratorTo> generatorToList = new ArrayList<GeneratorTo>();
        for (String tableName : tables.keySet()) {
            if ((null != project.getDbContainTable() && !project.getDbContainTable().contains(tableName))
                    || (null != project.getDbExcludeTable() && project.getDbExcludeTable().contains(tableName))) {
                continue;
            }
            GeneratorTo generatorTo = new GeneratorTo();
            generatorTo.setPoSerialVersionUID(StringUtil.genRandomNum(3) + System.nanoTime());
            List<FieldTo> fields = new ArrayList<FieldTo>();
            String minTn = StringUtil.hump4Underline(tableName);

            String tableRemark = null;
            if (!StringUtil.isBlank(tables.get(tableName))) {
                tableRemark = "/** " + tables.get(tableName) + " **/\n";
            }
            generatorTo.setRemark(tableRemark);
            //TODO  此处写死ID
            generatorTo.setIdField("#{id}");
            String capTn = StringUtil.capitalize(minTn);
            generatorTo.setAlias(minTn);
            generatorTo.setAliasCapFirst(capTn);
            generatorTo.setTableName(tableName);
            generatorTo.setPoName(capTn + "Po");
            // 设置PO的包路径
            generatorTo.setPoPkg((project.getPackagePath() + ".model.po").replace(SLASH, DOT));

            generatorTo.setQoPkg((project.getPackagePath() + ".model.qo").replace(SLASH, DOT));
            generatorTo.setQoName(capTn + "Qo");
            generatorTo.setToPkg((project.getPackagePath() + ".model.to").replace(SLASH, DOT));

            generatorTo.setMapperName("I" + capTn + "Mapper");
            generatorTo.setMapperPkg((project.getPackagePath() + ".mapper").replace(SLASH, DOT));

            generatorTo.setServiceName(capTn + "Service");
            generatorTo.setServicePkg((project.getPackagePath() + ".service").replace(SLASH, DOT));

            generatorTo.setControllerName(capTn + "Controller");
            generatorTo.setControllerPkg((project.getPackagePath() + ".controller").replace(SLASH, DOT));
            generatorTo.setControllerSerialVersionUID(StringUtil.genRandomNum(3) + System.nanoTime());

            Map<String, String> colns = dbUtil.getColumns(tableName, isComment);
            String column = "";
            List<String> importPkgs = new ArrayList<String>();
            for (String key : colns.keySet()) {
                FieldTo fieldTo = new FieldTo();
                if (isComment) {
                    String comm = key.substring(key.indexOf(" ") + 1);
                    if (!StringUtil.isBlank(comm)) {
                        fieldTo.setRemark("/** " + comm + " */");
                    }
                    column = key.substring(0, key.indexOf(" "));
                } else {
                    column = key;
                }
                String fn = StringUtil.hump4Underline(column);
                String javaType;
                if (column.equalsIgnoreCase("id")) {
                    javaType = DbConstant.FIELD_TYPE_INT;
                } else {
                    javaType = colns.get(key);
                }
                fieldTo.setColumn(column);
                fieldTo.setFieldName(fn);
                fields.add(fieldTo);

                fieldTo.setJavaType(javaType);

                if (javaType.equals(DbConstant.FIELD_TYPE_DATE) && !importPkgs.contains(importDate)) {
                    importPkgs.add(importDate);
                }
                if (javaType.equals(DbConstant.FIELD_TYPE_BIGDECIMAL) && !importPkgs.contains(importBigDecimal)) {
                    importPkgs.add(importBigDecimal);
                }
            }
            Collections.sort(fields);
            generatorTo.setFields(fields);
            generatorTo.setPoImportPkgs(importPkgs);
            generatorToList.add(generatorTo);
        }
        // 进行排序处理
        Collections.sort(generatorToList);
        return generatorToList;
    }

}
